import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Divider,
  Input,
  Row,
  Select,
  DatePicker,
  Modal,
  message,
  Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const FormItem = Form.Item;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { pathname } = window.location;
interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterProblemList: any;
  INITINFO: any;
  checkPerm: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  current: number;
  pageSize: number | undefined;
  formValues: any;
  orderInfo: any;
  problemDialog: boolean;
  rowId:number;
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    logisCenterProblemList,
    common: { INITINFO, checkPerm },
    global: { screen },
    loading,
  }: any) => ({
    logisCenterProblemList,
    INITINFO,
    checkPerm,
    screen,
    loading: loading.effects['logisCenterProblemList/fetch'],
  }),
)
class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: '运单号',
      dataIndex: 'expCode',
      width: 130,
      render: (text: any, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleShowProblem(record.id, text)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
    },
    {
      title: '问题件类型',
      dataIndex: 'problemDesc',
      width: 110,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '联系方式',
      dataIndex: 'consigneePhone',
      width: 120,
    },
    {
      title: '入库时间',
      dataIndex: 'inTime',
      width: 180,
      render(text: string, record: any) {
        if (record.delayWarning) {
          return <span style={{ color: 'red' }}>{text || '--'}</span>;
        }
        return <span>{text || '--'}</span>;
      },
    },
    {
      title: '存放位置',
      dataIndex: 'address',
      width: 180,
      render: (text: any, record: any) => {
        const pkgNum = record.pkgNum === '0' || !record.pkgNum ? '' : ` ${record.pkgNum}`;
        const pkgText = record.storageType !== 5 ? pkgNum : '';
        const address = text ? text + pkgText : '--';

        return (
          <Tooltip title={address}>
            <div className="wordOmit">{address}</div>
          </Tooltip>
        );
      },
    },
    {
      title: '处理状态',
      dataIndex: 'statusName',
      width: 100,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      width: 140,
      fixed: 'right',
      dataIndex: 'id',
      render: (text: any, record: any) => (
        <div>
          <span
            className="operLink"
            onClick={() => this.handleShowProblem(text, record.expCode)}
          >
            详情
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleOpenProblem(record)}>
            问题件处理
          </span>
        </div>
      ),
    },
  ];

  state: TableListState = {
    current: 1,
    pageSize: 20,
    formValues: {},
    orderInfo: {},
    problemDialog: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;

    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || 20,
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { logisCenterProblemList: { data } } = this.props;
    if (data?.list?.length) return;

    this.fetchLogisList();
    this.fetchTypeList();
    this.fetchExpressList();
    this.fetchProblemList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchProblemList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      formValues: {
        startTime,
        endTime,
        batchDate,
        logisId,
        expressId,
        problemType,
        status,
        ...others
      },
    } = this.state;

    if (startTime) {
      others.start_end_time = [moment(startTime), endTime ? moment(endTime) : ''];
    } else {
      others.start_end_time = [
        moment(
          moment()
            .subtract(7, 'days')
            .format('YYYY-MM-DD 00:00:00'),
        ),
        '',
      ];
    }

    if (startTime === '') others.start_end_time = ['', ''];

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  };

  // 获取物流中心列表
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchLogisList' });
  };

  // 获取问题件类型
  fetchTypeList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'logisCenterProblemList/typeList' });
  };

  // 获取问题件类型
  fetchProcessStatus = (problemType: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemList/processStatus',
      payload: { problemType },
    });
  };

  // 获取快递公司列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchExpressList2' });
  };

  // 获取数据
  fetchProblemList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemList/fetch',
      payload: this.getQueryParams(),
    });
  };

  // 获取查询参数
  getQueryParams = () => {
    const { formValues, current: pageIndex, pageSize } = this.state;
    const params = { ...formValues, pageIndex, pageSize };

    if (params.startTime === undefined) {
      params.startTime = moment().subtract(7, 'days').format('YYYY-MM-DD 00:00:00');
    }

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.start_end_time) {
        if (fieldsValue.start_end_time[0]) {
          fieldsValue.startTime = moment(fieldsValue.start_end_time[0]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          fieldsValue.startTime = '';
        }

        if (fieldsValue.start_end_time[1]) {
          fieldsValue.endTime = moment(fieldsValue.start_end_time[1]).format('YYYY-MM-DD HH:mm:ss');
        } else {
          fieldsValue.endTime = '';
        }
      } else {
        fieldsValue.startTime = '';
        fieldsValue.endTime = '';
      }

      delete fieldsValue.start_end_time;

      const query = { page: 1, ...fieldsValue };
      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '问题件管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '问题件管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  /**
   * 查看快递
   */
  handleShowProblem = (id: number, expCode: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${expCode}`,
      url: `${pathname}/detail/${id}`,
    });
  };

  /**
   * 问题件类型
   */
  handleTypeList = () => {
    router.push(`${pathname}/problemList`);
  };

  // 分页
  onSelectChange = (current: number, pageSize: number | undefined) => {
    const { formValues } = this.state;
    const query = {
      ...formValues,
      page: current,
      psize: pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '问题件管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  /**
   * 打开设置问题件弹窗
   */
  handleOpenProblem = (orderInfo: any) => {
    const new_orderInfo = { ...orderInfo };
    new_orderInfo.status = 0;

    this.setState({ orderInfo: new_orderInfo, problemDialog: true },
      () => this.fetchProcessStatus(new_orderInfo.problemType));
  };

  /**
   * 关闭设置问题件弹窗
   */
  handleCloseProblem = () => this.setState({ problemDialog: false, orderInfo: {} });

  /**
   * 设置问题件
   */
  handleAddProblem = () => {
    const { orderInfo } = this.state;

    if (!orderInfo.problemType) {
      message.error('请选择问题类型');
      return;
    }

    if (!orderInfo.remark) {
      message.error('备注不能为空');
      return;
    }

    if (orderInfo.status === 0) {
      const { logisCenterProblemList: { processStatus } } = this.props;
      const processStatusKeys = Object.keys(processStatus) || [];

      [orderInfo.status] = [Number(processStatusKeys[0])];
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterProblemList/addRecord',
      payload: {
        query: this.getQueryParams(),
        params: _.pick(orderInfo, ['orderId', 'problemType', 'status', 'remark']),
      },
    });

    this.handleCloseProblem();
  };

  /**
   * 选择问题件类型
   */
  handleChangeProblemType = (value: string) => {
    const { orderInfo } = this.state;
    orderInfo.problemType = value;
    this.setState({ orderInfo }, () => this.fetchProcessStatus(value));
  };

  /**
   * 选择处理状态
   */
  handleChangeStatus = (value: string) => {
    const { orderInfo } = this.state;
    orderInfo.status = Number(value);
    this.setState({ orderInfo });
  };

  /**
   * 输入备注
   */
  handleChangeRemark = (e: any) => {
    const { orderInfo } = this.state;
    orderInfo.remark = e.target.value;
    this.setState({ orderInfo });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { logisList, expressList },
      logisCenterProblemList: { typeList },
    } = this.props;


    const statusArr = {
      1: '待处理',
      2: '待用户取件',
      3: '待退回快递公司',
      4: '待进一步核实',
      10: '已结束',
    };

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <FormItem label="入库起止时间" colon={false}>
              {getFieldDecorator('start_end_time')(
                <RangePicker
                  showTime
                  placeholder={['开始时间', '截止时间']}
                  style={{ width: '100%' }}
                  format="YYYY/MM/DD HH:mm:ss"
                  disabledDate={timeLimit}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　　问题类型" colon={false}>
              {getFieldDecorator('problemType')(
                <Select allowClear placeholder="请选择">
                  {typeList.map((type: any) => (
                    <Option key={type.id} value={String(type.id)}>
                      {type.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="　　　运单号" colon={false}>
              {getFieldDecorator('expCode')(
                <Input allowClear placeholder="请输入" />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　　物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {logisList.map((item: any) => (
                    <Option value={String(item.id)} key={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　　快递公司" colon={false}>
              {getFieldDecorator('expressId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {expressList.map((express: any) => (
                    <Option value={String(express.id)} key={express.id}>
                      {express.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <FormItem label="　　处理状态" colon={false}>
              {getFieldDecorator('status')(
                <Select allowClear placeholder="请选择">
                  {Object.keys(statusArr).map(key => (
                    <Option key={String(key)} value={String(key)}>
                      {statusArr[key]}
                    </Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="　投递人手机" colon={false}>
              {getFieldDecorator('courierPhone')(
                <Input
                  allowClear
                  type="number"
                  placeholder="请输入"
                  style={{ width: '100%' }}
                />,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 渲染设置问题件
  renderProblemModalElem = () => {
    const { problemDialog, orderInfo } = this.state;
    const { logisCenterProblemList: { typeList, processStatus } } = this.props;
    const processStatusKeys = Object.keys(processStatus) || [];

    return (
      <Modal
        title="设置问题件"
        visible={problemDialog}
        destroyOnClose
        onOk={this.handleAddProblem}
        onCancel={this.handleCloseProblem}
      >
        <Form className="tableListForm">
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="　运单号" colon={false}>
                <Input allowClear disabled value={orderInfo.expCode} />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="问题类型" colon={false}>
                <Select onChange={this.handleChangeProblemType} value={orderInfo.problemType}>
                  {typeList.map((item: any) => (
                    <Option key={item.id} value={item.id}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="联系方式" colon={false}>
                <Input
                  disabled
                  allowClear
                  type="number"
                  placeholder="请输入"
                  value={orderInfo.consigneePhone}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="处理状态" colon={false}>
                <Select
                  placeholder="请选择"
                  defaultValue={processStatusKeys[0]}
                  onChange={this.handleChangeStatus}
                >
                  {processStatusKeys.map((key: any) => (
                    <Option key={key} value={key}>
                      {processStatus[key]}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Form.Item label="　　备注" colon={false}>
                <TextArea rows={4} value={orderInfo.remark} onChange={this.handleChangeRemark} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  };

  render() {
    const { current, pageSize } = this.state;
    const { logisCenterProblemList: { data }, screen, loading } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />
        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleTypeList}
            >
              问题类型管理
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1200 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        {this.renderProblemModalElem()}
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
